<template>
	<wd-toast />
	<wd-form ref="form" :model="model" custom-class="px-4 mt-4">
		<wd-cell-group border>
			<wd-input label="用户名" label-width="100px" prop="username" clearable v-model="model.username"
				placeholder="请输入用户名" :rules="[{ required: true, message: '请填写用户名' }]" />
			<wd-input label="邮箱" label-width="100px" prop="email" clearable v-model="model.email" placeholder="请输入邮箱"
				:rules="[{ required: true, message: '请填写邮箱' }]" />
			<wd-input label="密码" label-width="100px" prop="password" show-password clearable v-model="model.password"
				placeholder="请输入密码" :rules="[{ required: true, message: '请填写密码' }]" />
			<view class="flex items-center">
				<wd-input label="验证码" label-width="100px" prop="captcha" clearable v-model="model.captcha"
					placeholder="请输入验证码" :rules="[{required:true,message:'请填写验证码'}]" />
				<image class="w-134px h-44px shrink-0" @click="refreshCaptcha" :src=" captchaUrl" />
			</view>
		</wd-cell-group>
		<view class="footer mt-4">
			<wd-button type="primary" size="large" @click="handleSubmit" block>注册</wd-button>
		</view>
		<view class="flex justify-center mt-2">
			有账号？
			<view class="text-blue" @click="toLogin">
				去登录
			</view>
		</view>

	</wd-form>
</template>

<script setup>
	import {
		useToast
	} from "wot-design-uni";
	import {
		ref
	} from "vue";
	import {
		request
	} from "../../utils/request";
	import {
		getRegisterCaptcha,
		register
	} from '../../api/auth'
	const toast = useToast();
	const model = ref({});
	const form = ref({});
	const captchaUrl = ref('');

	const refreshCaptcha = () => {
		getRegisterCaptcha(Date.now()).then(res => {
			captchaUrl.value = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(res)}`;
		})
	};

	// 初始化时获取验证码
	refreshCaptcha();
	const toLogin = () => {
		uni.redirectTo({
			url: "/pages/login/login"
		})
	}
	const handleSubmit = () => {
		form.value
			.validate()
			.then(({
				valid,
				errors
			}) => {
				if (!valid) return;
				register(model.value).then(res => {
					if (res.status === 200) {
						toast.success("注册成功")
						setTimeout(()=>{
							toLogin();
						},1500) 
					}
				})
			})
	}
</script>

<style>

</style>